<template>
  <div id="MyNotesPage">
    <a-row :gutter="[16, 16]">
      <!-- 左侧边栏 -->
      <a-col :span="6">
        <a-card title="分类">
          <template #extra>
            <a-button type="link" @click="handleCategoryReset">重置</a-button>
          </template>
          <a-radio-group v-model:value="searchParams.categoryId" @change="handleSearch">
            <a-space direction="vertical">
              <a-radio :value="undefined">全部</a-radio>
              <a-radio v-for="category in categoryList" :key="category.id" :value="category.id">
                {{ category.categoryName }}
              </a-radio>
            </a-space>
          </a-radio-group>
        </a-card>

        <div style="margin-bottom: 16px"></div>

        <a-card title="系统标签">
          <template #extra>
            <a-button type="link" @click="handleTagReset">重置</a-button>
          </template>
          <a-space wrap>
            <a-tag
              v-for="tag in systemTagList"
              :key="tag.id"
              :color="isTagSelected(tag) ? 'blue' : undefined"
              style="cursor: pointer; margin-bottom: 8px"
              @click="handleTagClick(tag)"
            >
              {{ tag.tagName }}
            </a-tag>
          </a-space>
        </a-card>

        <div style="margin-bottom: 16px"></div>

        <a-card title="我的标签">
          <template #extra>
            <a-button type="link" @click="handleMyTagReset">重置</a-button>
          </template>
          <a-space wrap>
            <a-tag
              v-for="tag in myTagList"
              :key="tag.id"
              :color="isTagSelected(tag) ? 'blue' : undefined"
              style="cursor: pointer; margin-bottom: 8px"
              @click="handleTagClick(tag)"
            >
              {{ tag.tagName }}
            </a-tag>
          </a-space>
        </a-card>
      </a-col>

      <!-- 右侧内容区 -->
      <a-col :span="18">
        <!-- 搜索栏 -->
        <a-input-search
          v-model:value="searchParams.searchText"
          placeholder="搜索笔记标题或内容"
          enter-button
          @search="handleSearch"
          style="margin-bottom: 16px"
        />

        <!-- 笔记列表 -->
        <a-list
          :data-source="noteList"
          :pagination="pagination"
          :loading="loading"
          item-layout="vertical"
        >
          <template #renderItem="{ item }">
            <a-list-item @click="goToNoteDetail(item.id)" class="clickable-item">
              <template #extra>
                <div class="cover-wrapper">
                  <div
                    class="delete-button"
                    v-if="isNoteOwner(item)"
                    @click.stop="handleDelete(item)"
                  >
                    <DeleteOutlined />
                  </div>
                  <img
                    v-if="item.cover"
                    :src="item.cover"
                    alt="cover"
                    style="width: 200px; max-height: 150px; object-fit: cover"
                  />
                </div>
              </template>
              <a-list-item-meta>
                <template #title>
                  <div class="title-wrapper" style="margin-bottom: 7px">
                    <span class="note-title">{{ item.title }}</span>
                    <div class="status-tags">
                      <a-tag v-if="item.visibility === 1" color="blue">公开</a-tag>
                      <a-tag v-else color="default">私密</a-tag>
                      <a-tag
                        v-if="item.visibility === 1"
                        :color="getReviewStatusColor(item.reviewStatus)"
                      >
                        {{ getReviewStatusText(item.reviewStatus) }}
                      </a-tag>
                    </div>
                  </div>
                </template>
                <template #avatar>
                  <div class="avatar-container">
                    <a-avatar :src="item.user?.userAvatar || '/avatar.png'">
                      {{ item.user?.userName?.charAt(0)?.toUpperCase() || 'U' }}
                    </a-avatar>
                    <span class="avatar-username">{{ item.user?.userName || '匿名用户' }}</span>
                  </div>
                </template>
                <template #description>
                  <a-space>
                    <span>{{ dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
                    <a-divider type="vertical" />
                    <a-space>
                      <template v-if="item.tagList && item.tagList.length > 0">
                        <a-tag v-for="tag in item.tagList" :key="tag.id">
                          {{ tag.tagName }}
                        </a-tag>
                      </template>
                    </a-space>
                  </a-space>
                </template>
              </a-list-item-meta>
              <div class="note-content">{{ item.content?.substring(0, 200) }}...</div>
            </a-list-item>
          </template>
        </a-list>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { createVNode, onMounted, reactive, ref } from 'vue'
import { message, Modal } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  deleteNoteUsingPost,
  listMyNotesVoByPageUsingPost,
  listNoteTagsCategoryUsingGet,
} from '@/api/notesController'
import { listMyTagsVoByPageUsingPost } from '@/api/tagsController'
import { useRouter } from 'vue-router'
import { DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore'

const router = useRouter()
const loginUserStore = useLoginUserStore()

// 加载状态
const loading = ref(false)

// 笔记列表数据
const noteList = ref<API.MyNoteVO[]>([])
const total = ref(0)

// 分类和标签数据
const categoryList = ref<API.Categories[]>([])
const systemTagList = ref<API.Tags[]>([])
const myTagList = ref<API.Tags[]>([])

// 搜索参数
const searchParams = reactive<API.NotesQueryRequest>({
  current: 1,
  pageSize: 8,
  sortField: 'create_time',
  sortOrder: 'descend',
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 8,
  total: 0,
  onChange: (page: number, pageSize: number) => {
    searchParams.current = page
    searchParams.pageSize = pageSize
    fetchNotes()
  },
})

// 获取笔记列表
const fetchNotes = async () => {
  loading.value = true
  try {
    const res = await listMyNotesVoByPageUsingPost(searchParams)
    if (res.data.code === 0 && res.data.data) {
      noteList.value = res.data.data.records ?? []
      total.value = res.data.data.total ?? 0
      pagination.total = total.value
    } else {
      message.error('获取笔记列表失败：' + res.data.message)
    }
  } catch (error: any) {
    message.error('获取笔记列表失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 获取分类和系统标签
const fetchTagsCategory = async () => {
  try {
    const res = await listNoteTagsCategoryUsingGet()
    if (res.data.code === 0 && res.data.data) {
      categoryList.value = res.data.data.categoriesList ?? []
      systemTagList.value = res.data.data.tagsList ?? []
    }
  } catch (error: any) {
    message.error('获取分类和标签失败：' + error.message)
  }
}

// 获取我的标签
const fetchMyTags = async () => {
  try {
    const res = await listMyTagsVoByPageUsingPost({
      pageSize: 50,
      current: 1,
    })
    if (res.data.code === 0 && res.data.data) {
      myTagList.value = res.data.data.records ?? []
    }
  } catch (error: any) {
    message.error('获取我的标签失败：' + error.message)
  }
}

// 判断标签是否被选中
const isTagSelected = (tag: API.Tags) => {
  return searchParams.tags?.some((t) => t.id === tag.id) ?? false
}

// 处理标签点击
const handleTagClick = (tag: API.Tags) => {
  if (!searchParams.tags) {
    searchParams.tags = []
  }
  const index = searchParams.tags.findIndex((t) => t.id === tag.id)
  if (index > -1) {
    searchParams.tags.splice(index, 1)
  } else {
    searchParams.tags.push(tag)
  }
  handleSearch()
}

// 重置分类
const handleCategoryReset = () => {
  searchParams.categoryId = undefined
  handleSearch()
}

// 重置系统标签
const handleTagReset = () => {
  searchParams.tags = searchParams.tags?.filter((tag) => {
    return myTagList.value.some((t) => t.id === tag.id)
  })
  handleSearch()
}

// 重置我的标签
const handleMyTagReset = () => {
  searchParams.tags = searchParams.tags?.filter((tag) => {
    return systemTagList.value.some((t) => t.id === tag.id)
  })
  handleSearch()
}

// 处理搜索
const handleSearch = () => {
  searchParams.current = 1
  fetchNotes()
}

// 获取审核状态文本
const getReviewStatusText = (status?: number) => {
  const statusMap: Record<number, string> = {
    0: '无需审核',
    1: '审核中',
    2: '已通过',
    3: '已拒绝',
  }
  return statusMap[status ?? 0] ?? '无需审核'
}

// 获取审核状态颜色
const getReviewStatusColor = (status?: number) => {
  const colorMap: Record<number, string> = {
    0: 'blue',
    1: 'warning',
    2: 'success',
    3: 'error',
  }
  return colorMap[status ?? 0] ?? 'blue'
}

// 跳转到笔记详情页
const goToNoteDetail = (id?: number) => {
  if (id) {
    window.open(`/note/${id}`, '_blank')
  }
}

// 检查是否为笔记作者
const isNoteOwner = (note: API.NotesVO) => {
  return loginUserStore.loginUser.id === note.user?.id
}

// 处理笔记删除
const handleDelete = (note: API.NotesVO) => {
  Modal.confirm({
    title: '确认删除',
    icon: createVNode(ExclamationCircleOutlined),
    content: '确定要删除这篇笔记吗？删除后将无法恢复。',
    okText: '确认',
    okType: 'danger',
    cancelText: '取消',
    okButtonProps: {
      style: { outline: 'none' }
    },
    async onOk() {
      try {
        const res = await deleteNoteUsingPost({
          id: note.id,
        })
        if (res.data.code === 0) {
          message.success('删除成功')
          // 重新加载笔记列表
          await fetchNotes()
        } else {
          message.error('删除失败：' + res.data.message)
        }
      } catch (error: any) {
        message.error('删除失败：' + error.message)
      }
    },
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchNotes()
  fetchTagsCategory()
  fetchMyTags()
})
</script>

<style scoped>
#MyNotesPage {
  padding: 24px;
}

.clickable-item {
  cursor: pointer;
  transition: background-color 0.3s;
}

.clickable-item:hover {
  background-color: rgba(0, 0, 0, 0.02);
}

.cover-wrapper {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.delete-button {
  position: absolute;
  top: 1px;
  right: 8px;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 8px;
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 1;
  transition: all 0.3s;
  display: none;
}

.delete-button:hover {
  background-color: #ff4d4f;
  color: white;
}

.clickable-item:hover .delete-button {
  display: flex;
  align-items: center;
  justify-content: center;
}

.title-wrapper {
  display: flex;
  align-items: center;
  gap: 24px;
}

.note-title {
  font-size: 16px;
  font-weight: 500;
  color: #1890ff;
}

.status-tags {
  display: flex;
  gap: 8px;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.avatar-username {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.65);
  white-space: nowrap;
  max-width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.note-content {
  color: #666;
  margin-top: 8px;
}

:deep(.ant-list-item-meta-title) {
  margin-bottom: 4px !important;
}

:deep(.ant-list-item) {
  padding: 16px !important;
}

:deep(.ant-list-item-meta) {
  margin-bottom: 12px;
}

/* :deep(.ant-btn:focus) {
  outline: none !important;
  box-shadow: none !important;
} */
</style>
